<?php

    // +----------------------------------------------------------------------
    // | 邮箱兑换
    // +----------------------------------------------------------------------
    // | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
    // +----------------------------------------------------------------------
    // | Author: 微尘 <yicmf@qq.com>
    // +----------------------------------------------------------------------

    namespace app\event\ucenter;

    use app\model\ucenter\User as UserModel;
    use think\facade\Db;
    use think\Exception;
    use app\common\event\Base;
    use app\model\ucenter\Exchange as ExchangeModel;
    use app\pay\model\Coupon as CouponModel;
    use app\event\ucenter\UserPoint as UserPointEvent;

    class Exchange extends Base
    {
        protected $user;


        /**
         * 积分兑换
         * @param      $param
         * @param UserModel $user
         * @return mixed
         * @author  : 微尘 <yicmf@qq.com>
         * @datetime: 2019/3/3 20:04
         */
        public function get($param, $user)
        {
            try {
                Db::startTrans();
                $exchange = ExchangeModel::find($param['id']);
                if (!$exchange)
                {
                    throw new Exception('兑换礼品不存在');
                }
                if ($exchange['stock'] < 1)
                {
                    throw new Exception('兑换礼品库存不足');
                }
                // 积分判断
                if ($user['point'] < $exchange['point'])
                {
                    throw new Exception('积分不足');
                }
                // TODO:多种类型兑换
                if (1 == $exchange['type'])
                {
                    $data = $this->getCoupon($exchange, $user);
                }else{
                    throw new Exception('兑换类型不存在');
                }
                // 库存变更
                $exchange['stock'] = $exchange['stock'] - 1;
                $exchange['sale'] = $exchange['sale'] + 1;
                $exchange->save();
                $param['point'] = -$exchange['point'];
                $param['relation_id'] = $exchange['id'];
                //记录行为&积分处理
                Action::log('user_point_exchange', $user, $param);
                $point = [];
                $point['change_code'] = 'exchange';
                $point['relation_id'] = $exchange['id'];
                $point['point'] = -$exchange['point'];
                UserPointEvent::change($point,$user);
                // 通知
                Db::commit();
            } catch ( \Exception $e ) {
                Db::rollback();
                $data['message'] = $e->getMessage();
                $data['code'] = 1;
            }
            return $data;
        }

        protected function getCoupon($exchange,$user)
        {
            // 兑换优惠券
            $coupon = CouponModel::where('id',$exchange['relation_id'])->find();
            if(!$coupon){
                throw new Exception('未发现优惠券，或者已经过期');
            }
            // 确认是否有剩余
            if ($coupon['total_number'] <= $coupon->cards()->count('*')) {
                throw new \Exception('当前优惠券已经领取完毕');
            }
            //查询当前用户是否领取超量
            if ($coupon['limit'] && $coupon['limit'] > $coupon->cards()->where('user_id',$user['id'])->where('status',1)->count('*'))
            {
                throw new Exception('您已经超过限定领取数量');
            }

            // 创建一个优惠券
            $card = [];
            $card['name'] = $coupon['name'];
            $card['introduce'] = $coupon['introduce'];
            $card['body'] = $coupon['body'];
            $card['store_id'] = $coupon['user_id'];
            $card['user_id'] = $user['id'];
            $card['worth'] = $coupon['worth'];
            $card['start_price'] = $coupon['start_price'];
            $card['effective_time'] = $coupon['effective_time'];
            $card['coupon_template_id'] = $coupon['coupon_template_id'];
            if (!$coupon->cards()->save($card)) {
                throw new Exception('领取优惠券异常');
            }
            $coupon['left_number'] = $coupon['total_number'] - $coupon->cards()->count('*');
            if (!$coupon->save()) {
//                throw new Exception('优惠券信息保存失败',211109);
            }
            $data['data']['coupon'] = $coupon;
            $data['data']['card'] = $card;
            $data['message'] = '优惠券兑换成功';
            $data['code'] = 0;
            return $data;
        }
    }
